import { createBoard, findPath, block } from "./board/llk";
import './style.css'

const app = document.querySelector('#app') as HTMLDivElement

const board = createBoard()

let boardDOM : HTMLDivElement = document.createElement('div')

let toastDOM: HTMLDivElement = document.createElement('div')

toastDOM.classList.add('game-toast', 'hide')

toastDOM.textContent = '胜利！'

const dataCache = [] as any[]

let prohibitClick = false

const isWinning = () => {

  const winning = board.every(row => row.every(col => col.type === -1))

    if (winning) {
      toastDOM.classList.remove('hide')
      boardDOM.classList.add('winning')
    }
}

const centralCalc = (pos: string[], value: string, el: HTMLDivElement) => {
  dataCache.push({
    pos,
    value,
    el
  })

  console.log('caching?', dataCache)

  if (dataCache.length === 2) {
    const [a, b] = dataCache
    dataCache.length = 0 // 无论是否匹配，都会被清空
    
    if (a.value === b.value) {

      if (a.el === b.el) {
        setTimeout(() => {
          a.el.classList.remove('clicked-piece')
          b.el.classList.remove('clicked-piece')
        }, 500)
        return
      }

      prohibitClick = true

      console.log('having data?', a, b)

      const path = [] as any[]

      const isOk = findPath(a.pos.map(Number), b.pos.map(Number), board, path)

      console.log('found path?', isOk, path)

      if (!isOk) {
        setTimeout(() => {
          prohibitClick = false
          a.el.classList.remove('clicked-piece')
          b.el.classList.remove('clicked-piece')
        }, 500)
        return
      }

      path.forEach(([row, col]) => {
        console.log('path finding', row, col)

        boardDOM.children[row].children[col].classList.add('path-piece')
      })

      prohibitClick = true
      setTimeout(() => {

        path.forEach(([row, col]) => {
          boardDOM.children[row].children[col].classList.remove('path-piece')
        })

        const [ra, ca] = a.pos
        const [rb, cb] = b.pos

        // 清空a, b两个逻辑节点
        board[ra][ca] = block(-1, ra, ca)
        board[rb][cb] = block(-1, rb, cb)

        // 清空a, b两个DOM节点
        boardDOM.children[ra].children[ca].classList.remove('path-piece', 'number-piece', 'clicked-piece')
        boardDOM.children[ra].children[ca].textContent = ''
        
        boardDOM.children[rb].children[cb].classList.remove('path-piece', 'number-piece', 'clicked-piece')
        boardDOM.children[rb].children[cb].textContent = ''

        prohibitClick = false

        // 游戏结束校验
        isWinning()
      }, 500)

      // a.el.classList.add('match-piece')
      // b.el.classList.add('match-piece')
      
    } else {
      prohibitClick = true
      setTimeout(() => {
        a.el.classList.remove('clicked-piece')
        b.el.classList.remove('clicked-piece')
        prohibitClick = false
      }, 500)
    }
  }
}

const createPieceDOM = (pic: any) => {
  const el = document.createElement('div')
  const isOuter = pic.type === -1
  el.classList.add('game-piece')
  el.textContent = isOuter ? '' : String(pic.type)

  if (!isOuter) {
    el.classList.add('number-piece')
    el.setAttribute('data-val', `${pic.type}`)
    el.setAttribute('data-loc', `${pic.row},${pic.col}`)
  }
  return el
}

const createRowDOM = (row: {type: number}[]) => {
  const el = document.createElement('div')
  el.classList.add('game-row')
  
  row.forEach((e) => {
    const pic = createPieceDOM(e)
    el.appendChild(pic)
  })

  return el
}

const createBoardDOM = (board: {type:number}[][]) => {
  const el = document.createElement('div')
  el.classList.add('game-board')

  board.forEach(row => {
    const picRow = createRowDOM(row)
    el.appendChild(picRow)
  })

  el.appendChild(toastDOM)

  return el
}

const appendEvent = (boardDOM: HTMLDivElement) => {
  const cb = (e: MouseEvent) => {
    if (prohibitClick) return;
    // 点击了
    const el = e.target as HTMLDivElement
    if (!el.dataset.loc) return;
    const value = el.dataset.val
    const pos = el.dataset.loc.split(',')
    el.classList.add('clicked-piece')

    console.log('clicked', pos, ' with value:', value)

    centralCalc(pos, value!, el)
  }
  boardDOM.addEventListener('click', cb)
}

const createResetButton = () => {
  const el = document.createElement('input')

  el.setAttribute('type', 'button')

  el.classList.add('reset-btn')

  el.value = '重新开始'

  el.addEventListener('click', () => {
    location.reload()
  })

  return el
}

const main = () => {
  boardDOM = createBoardDOM(board as {type:number}[][])
  appendEvent(boardDOM)

  app.appendChild(boardDOM)

  const resetBtn = createResetButton()

  document.body.appendChild(resetBtn)
}

main()